package com.atguigu.lease.web.app.intecepter;

import com.atguigu.lease.common.context.LoginSysUser;
import com.atguigu.lease.common.context.LoginSysUserContext;
import com.atguigu.lease.common.exception.define.BusException;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthenticationIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("access_token");
        if (accessToken == null) {
            throw new BusException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN.getCode(), ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN.getMessage());
        }
        Claims claims = JwtUtil.parseToken(accessToken);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginSysUser loginSysUser = new LoginSysUser(userId,username);
        LoginSysUserContext.setContex(loginSysUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginSysUserContext.removeContex();
    }
}
